﻿using NLog;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GuiZhou.ImageArchive.Update
{
    public partial class Form1 : Form
    {

        static IScheduler _scheduler;
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public Form1()
        {
            InitializeComponent();

            OpenJob();
            
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            logger.Info("开始手动更新");
            string ProcessKilledStr = ConfigurationManager.AppSettings["UpdateProgram"];
            ProcessUtils.ProcessKill(ProcessKilledStr);
            //var assembly = UpdateTool.GetAssembly();
            UpdateTool.CheckUpdate();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox1.Checked == true)
            {
                if(_scheduler != null && (_scheduler.IsShutdown || _scheduler.InStandbyMode))
                {
                    _scheduler.Start();
                }
            }
            else
            {
                if(_scheduler != null || _scheduler.IsStarted)
                {
                    _scheduler.Standby();
                }
            }
        }

        public void OpenJob()
        {
            var schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler();
            _scheduler.Start();

            IJobDetail job1 = JobBuilder.Create<UpdateJob>().WithIdentity("Job1", "Group1").Build();

            string cron = ConfigurationManager.AppSettings["CronExpression"];

            ITrigger trigger1 =
                TriggerBuilder.Create().WithIdentity("Trigger1", "Group1").WithCronSchedule(cron).Build();

            _scheduler.ScheduleJob(job1, trigger1);
            _scheduler.Start();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭调度器
            if(_scheduler != null)
            {
                if(_scheduler.IsStarted || _scheduler.InStandbyMode)
                {
                    _scheduler.Shutdown();
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            logger.Info("程序已启动！");
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
        }
    }
}
